package framwork

import (
	deploy "gingorm/proto/common"
	"gingorm/utils"
	"gorm.io/gorm"
	"strings"
)

type ComponentDBInfc interface {
	Init(ConfigPath string)error
	GetDBInstance(SqlName string)*gorm.DB
}

type ComponentDB struct {
	dbCfg *deploy.DataBaseConfig
	db map[string]*gorm.DB
}

func (c *ComponentDB) Init(ConfigPath string) error {
	//加载 database 的配置
	c.dbCfg = new(deploy.DataBaseConfig)
	err := utils.LoadProtoMessage(ConfigPath, c.dbCfg)
	if err != nil {
		return err
	}

	c.db = make(map[string]*gorm.DB)
	// 链接数据库
	for SqlType, DataBaseInfo := range c.dbCfg.DatabaseInfoMaps {
		err , db := utils.InstanceDB(SqlType, DataBaseInfo, gorm.Config{})
		if err != nil {
			return err
		}
		c.db[SqlType] = db
	}
	return nil
}

func (c *ComponentDB) GetDBInstance(SqlType string) *gorm.DB {
	return c.db[strings.ToLower(SqlType)]
}



